package zhenai

import (
    "bytes"
    "crawler/distribute/config"
    "crawler/engine"
    "crawler/zhenai/model"
    "github.com/PuerkitoBio/goquery"
    "log"
    "strconv"
    "strings"
)

func ParseCity(content []byte) engine.ParseResult {
    var result engine.ParseResult
    doc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(content))
    if err != nil {
        log.Printf("parse city page error:", err.Error())
        return result
    }
    
    doc.Find(".m-left .list-item").Each(func(i int, selection *goquery.Selection) {
        var profile model.Profile
        
        profile.Name = selection.Find("table th a").Text()
        
        selection.Find("table td").Each(func(j int, selection2 *goquery.Selection) {
            attr := selection2.Text()
            if strings.HasPrefix(attr, "性别：") {
                profile.Gender = string([]rune(attr)[3:])
            } else if strings.HasPrefix(attr, "居住地：") {
                profile.Location = string([]rune(attr)[4:])
            } else if strings.HasPrefix(attr, "年龄：") {
                profile.Age, _ = strconv.Atoi(string([]rune(attr)[3:]))
            } else if strings.HasPrefix(attr, "婚况：") {
                profile.Marriage = string([]rune(attr)[3:])
            } else if strings.HasPrefix(attr, "身   高：") {
                profile.Height, _ = strconv.Atoi(string([]rune(attr)[6:]))
            } else if strings.HasPrefix(attr, "学   历：") {
                profile.Edu = string([]rune(attr)[6:])
            } else if strings.HasPrefix(attr, "月   薪：") {
                salary := strings.Split(strings.Trim(string([]rune(attr)[6:]), "元"), "-")
                //fmt.Println(salary)
                if len(salary) == 2 {
                    profile.SalaryL, _ = strconv.Atoi(salary[0])
                    profile.SalaryH, _ = strconv.Atoi(salary[1])
                }
            }
        })
        
        result.Items = append(result.Items, profile)
    })
    
    doc.Find(".f-pager .m-page a").Each(func(i int, selection *goquery.Selection) {
        if selection.Text() == "下一页" {
            nextPage := selection.AttrOr("href", "")
            if nextPage != "" {
                result.Requests = append(result.Requests, engine.Request{
                    Url:    nextPage,
                    Parser: engine.NewFuncParser(config.ZhenAiParseCity, ParseCity),
                })
            }
        }
    })
    
    return result
}
